package com.indi.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.indi.common.utils.PageUtils;
import com.indi.common.utils.Query;
import com.indi.gulimall.product.dao.ProductAttrValueDao;
import com.indi.gulimall.product.entity.ProductAttrValueEntity;
import com.indi.gulimall.product.service.ProductAttrValueService;
import com.indi.gulimall.product.vo.web.SkuItemVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("productAttrValueService")
public class ProductAttrValueServiceImpl extends ServiceImpl<ProductAttrValueDao, ProductAttrValueEntity> implements ProductAttrValueService {
    @Resource
    private ProductAttrValueDao attrValueDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<ProductAttrValueEntity> page = this.page(
                new Query<ProductAttrValueEntity>().getPage(params),
                new QueryWrapper<ProductAttrValueEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<ProductAttrValueEntity> listBySpuId(Long spuId) {
        List<ProductAttrValueEntity> attrValues = this.list(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", spuId));
        return attrValues;
    }

    @Transactional
    @Override
    public void updateBySpuId(Long spuId, List<ProductAttrValueEntity> attrValues) {
        baseMapper.delete(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", spuId));

        List<ProductAttrValueEntity> attrValueList = attrValues.stream().map(attrValue -> {
            attrValue.setSpuId(spuId);
            return attrValue;
        }).collect(Collectors.toList());

        this.saveBatch(attrValueList);
    }

    @Override
    public List<SkuItemVO.SpuAttrGroupVO> getAttrWithGroupVO(Long categoryId, Long spuId) {
        List<SkuItemVO.SpuAttrGroupVO> attrGroupVOs = attrValueDao.getAttrWithGroupVO(categoryId, spuId);
        return attrGroupVOs;
    }

}